package com.stationpc.androidtvrecents

import android.app.ActivityManager
import android.app.Application
import android.app.usage.UsageStatsManager
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.util.concurrent.TimeUnit
import android.content.pm.ApplicationInfo

class RecentAppsViewModel(application: Application) : AndroidViewModel(application) {
    private val _recentApps = MutableLiveData<List<AppInfo>>()
    val recentApps: LiveData<List<AppInfo>> = _recentApps
    private val activityManager = getApplication<Application>().getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
    private val removedPackages = mutableSetOf<String>()

    fun loadRecentApps() {
        viewModelScope.launch {
            val apps = withContext(Dispatchers.IO) {
                getRecentApps()
            }
            _recentApps.value = apps.filterNot { app ->
                removedPackages.contains(app.packageName)
            }
        }
    }

    private fun getRecentApps(): List<AppInfo> {
        val context = getApplication<Application>()
        val usageStatsManager = context.getSystemService(Context.USAGE_STATS_SERVICE) as UsageStatsManager
        val endTime = System.currentTimeMillis()
        val startTime = endTime - TimeUnit.DAYS.toMillis(1)

        val excludePackages = setOf(
            context.packageName,
            "com.android.systemui",
            "com.android.packageinstaller",
            "com.spocky.projengmenu",
            "android",
            "com.android.settings"
        ) + removedPackages

        return usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, startTime, endTime)
            .filter { stat ->
                stat.lastTimeUsed > 0 &&
                !excludePackages.contains(stat.packageName) &&
                !isSystemApp(stat.packageName)
            }
            .sortedByDescending { it.lastTimeUsed }
            .distinctBy { it.packageName }
            .mapNotNull { stat ->
                try {
                    val packageManager = context.packageManager
                    val appInfo = packageManager.getApplicationInfo(stat.packageName, 0)
                    if ((appInfo.flags and ApplicationInfo.FLAG_SYSTEM) != 0) {
                        return@mapNotNull null
                    }
                    AppInfo(
                        packageName = stat.packageName,
                        label = packageManager.getApplicationLabel(appInfo).toString()
                    )
                } catch (e: PackageManager.NameNotFoundException) {
                    null
                }
            }
            .take(10)
    }

    private fun isSystemApp(packageName: String): Boolean {
        try {
            val packageManager = getApplication<Application>().packageManager
            val appInfo = packageManager.getApplicationInfo(packageName, 0)
            return (appInfo.flags and ApplicationInfo.FLAG_SYSTEM) != 0
        } catch (e: Exception) {
            return false
        }
    }

    fun openApp(position: Int) {
        _recentApps.value?.getOrNull(position)?.let { app ->
            val context = getApplication<Application>()
            val intent = context.packageManager.getLaunchIntentForPackage(app.packageName)
            intent?.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            intent?.let { context.startActivity(it) }
        }
    }

    fun removeApp(position: Int) {
        val currentList = _recentApps.value?.toMutableList() ?: return
        if (position in currentList.indices) {
            val app = currentList[position]
            try {
                // Add to removed packages set
                removedPackages.add(app.packageName)

                TasksUtils.removeTask(getApplication(),app.packageName)

//                // Kill background processes
//                activityManager.killBackgroundProcesses(app.packageName)
//
//                // Force stop if possible
//                activityManager.runningAppProcesses?.forEach { processInfo ->
//                    if (processInfo.processName == app.packageName) {
//                        android.os.Process.killProcess(processInfo.pid)
//                    }
//                }
//
//                // Try alternative force stop
//                try {
//                    Runtime.getRuntime().exec("am force-stop ${app.packageName}")
//                } catch (e: Exception) {
//                    e.printStackTrace()
//                }

                // Remove from current list
                currentList.removeAt(position)
                _recentApps.value = currentList
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }

    override fun onCleared() {
        super.onCleared()
        removedPackages.clear()
    }
}
